/*
 * 天气信息组件 - Weather Info Component
 * 显示天气预报和当前时间
 */
import {
  DEFAULT_WEATHER_DATA,
  FOSHAN_COORDINATES,
  getWeatherDescription,
  getWeatherIcon,
  LOADING_WEATHER_DATA,
} from '@/constants/weather';
import { CloudOutlined } from '@ant-design/icons';
import { Card } from 'antd';
import React, { useEffect, useState } from 'react';
import styles from './index.less';

interface WeatherInfoProps {
  className?: string;
}

const WeatherInfo: React.FC<WeatherInfoProps> = ({ className }) => {
  const [weatherData, setWeatherData] = useState(LOADING_WEATHER_DATA);
  const [currentTime, setCurrentTime] = useState('');
  const [isExpanded, setIsExpanded] = useState(false);

  // 获取天气数据
  const fetchWeatherData = async () => {
    try {
      // 使用免费的Open-Meteo API获取佛山天气
      const { latitude, longitude } = FOSHAN_COORDINATES;

      const response = await fetch(
        `https://api.open-meteo.com/v1/forecast?latitude=${latitude}&longitude=${longitude}&current=temperature_2m,relative_humidity_2m,weather_code,wind_speed_10m&daily=weather_code,temperature_2m_max,temperature_2m_min,sunrise,sunset&timezone=Asia/Shanghai&forecast_days=4`,
      );

      if (!response.ok) {
        throw new Error('天气数据获取失败');
      }

      const data = await response.json();
      const current = data.current;
      const daily = data.daily;

      // 格式化时间
      const formatTime = (timeString: string) => {
        return new Date(timeString).toLocaleTimeString('zh-CN', {
          hour: '2-digit',
          minute: '2-digit',
          hour12: false,
        });
      };

      // 格式化日期
      const formatDay = (dateString: string, index: number) => {
        const date = new Date(dateString);
        const today = new Date();
        const tomorrow = new Date(today);
        tomorrow.setDate(today.getDate() + 1);

        if (index === 0) return '今天';
        if (index === 1) return '明天';
        if (index === 2) return '后天';

        const weekdays = [
          '周日',
          '周一',
          '周二',
          '周三',
          '周四',
          '周五',
          '周六',
        ];
        return weekdays[date.getDay()];
      };

      setWeatherData({
        location: '广东省佛山市',
        temperature: `${Math.round(current.temperature_2m)}°C`,
        weather: getWeatherDescription(current.weather_code),
        icon: getWeatherIcon(current.weather_code),
        humidity: `${current.relative_humidity_2m}%`,
        windSpeed: `${Math.round(current.wind_speed_10m)} km/h`,
        sunrise: formatTime(daily.sunrise[0]),
        sunset: formatTime(daily.sunset[0]),
        forecast: daily.time.slice(0, 4).map((date: string, index: number) => ({
          day: formatDay(date, index),
          icon: getWeatherIcon(daily.weather_code[index]),
          high: `${Math.round(daily.temperature_2m_max[index])}°`,
          low: `${Math.round(daily.temperature_2m_min[index])}°`,
        })),
      });
    } catch (error) {
      console.error('获取天气数据失败:', error);
      setWeatherData(DEFAULT_WEATHER_DATA);
    }
  };

  useEffect(() => {
    // 获取天气数据
    fetchWeatherData();

    // 更新当前时间
    const updateCurrentTime = () => {
      const now = new Date();
      const optionsDate = { weekday: 'long' as const };
      const optionsTime = {
        hour: '2-digit' as const,
        minute: '2-digit' as const,
        hour12: false,
      };
      setCurrentTime(
        `${now.toLocaleDateString(
          'zh-CN',
          optionsDate,
        )}, ${now.toLocaleTimeString([], optionsTime)}`,
      );
    };

    updateCurrentTime();
    const timeInterval = setInterval(updateCurrentTime, 60000);

    // 清理定时器
    return () => {
      clearInterval(timeInterval);
    };
  }, []);

  return (
    <Card
      className={`${styles.card} ${styles.weatherCard} ${className || ''}`}
      onMouseEnter={() => setIsExpanded(true)}
      onMouseLeave={() => setIsExpanded(false)}
    >
      <div
        className={`${styles.weatherContainer} ${
          isExpanded ? styles.expanded : styles.collapsed
        }`}
      >
        {/* 收缩状态 - 显示位置和基本天气信息 */}
        <div className={styles.collapsedContent}>
          <div className={styles.locationCompact}>{weatherData.location}</div>
          <div className={styles.weatherCompact}>
            <span className={styles.weatherIconCompact}>
              {weatherData.icon}
            </span>
            <span className={styles.temperatureCompact}>
              {weatherData.temperature}
            </span>
          </div>
        </div>

        {/* 展开状态 - 显示完整天气信息 */}
        <div className={styles.expandedContent}>
          <div className={styles.weatherHeader}>
            <CloudOutlined className={styles.weatherIcon} />
            <span className={styles.weatherTitle}>天气预报</span>
          </div>

          <div className={styles.currentTime}>{currentTime}</div>

          <div className={styles.currentWeather}>
            <div className={styles.weatherIconMain}>{weatherData.icon}</div>
            <div className={styles.temperature}>{weatherData.temperature}</div>
          </div>

          <div className={styles.location}>{weatherData.location}</div>

          <div className={styles.sunInfo}>
            <div className={styles.sunrise}>
              <div className={styles.sunIcon}>☀️</div>
              <div className={styles.sunTime}>{weatherData.sunrise}</div>
            </div>
            <div className={styles.dayLength}>12小时15分</div>
            <div className={styles.sunset}>
              <div className={styles.sunIcon}>🌙</div>
              <div className={styles.sunTime}>{weatherData.sunset}</div>
            </div>
          </div>

          <div className={styles.weatherDetails}>
            <div className={styles.humidity}>湿度: {weatherData.humidity}</div>
            <div className={styles.windSpeed}>
              风速: {weatherData.windSpeed}
            </div>
          </div>

          <div className={styles.forecast}>
            {weatherData.forecast.map((item, index) => (
              <div key={index} className={styles.forecastDay}>
                <div className={styles.dayName}>{item.day}</div>
                <div className={styles.forecastIcon}>{item.icon}</div>
                <div className={styles.highTemp}>{item.high}</div>
                <div className={styles.lowTemp}>{item.low}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </Card>
  );
};

export default WeatherInfo;
